<script lang="ts" setup>
import type { AxiosRequestConfig } from '@vben/request';

import type { FormSchemaExt } from '#/api/common/model/validateModel';

import { ref, unref } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { useVbenForm } from '#/adapter/form';
import { DefApplicationApi, DefApplicationConfig, listByBizId } from '#/api';
import { getValidateRuleByVben } from '#/api/common/validate';
import { ActionEnum, FileBizTypeEnum } from '#/enums/commonEnum';
import { useMessage } from '#/hooks/web/useMessage';
import { $t } from '#/locales';

import { formSchamas } from '../schemas/index';

const record = ref();
const type = ref<ActionEnum>(ActionEnum.ADD);
const { createMessage } = useMessage();
const gridApi = ref();

const [EditForm, formApi] = useVbenForm({
  showDefaultActions: false,
  ...formSchamas,
});

async function updateRules(
  Api: AxiosRequestConfig,
  customRules?: FormSchemaExt[],
) {
  const list = await getValidateRuleByVben({ Api, customRules });
  formApi.updateSchema(list);
}

const [Modal, modalApi] = useVbenModal({
  async onOpenChange(isOpen) {
    type.value = modalApi.getData()?.type ?? false;
    record.value = isOpen ? modalApi.getData()?.record || {} : {};
    gridApi.value = isOpen ? modalApi.getData()?.gridApi : null;
    if (isOpen && type.value) {
      const data = { ...record.value };

      if (unref(type) !== ActionEnum.ADD) {
        const appendixIcons = await listByBizId({
          bizId: record.value.id,
          bizType: FileBizTypeEnum.DEF_APPLICATION_LOGO,
        });
        data.appendixIcon = appendixIcons?.[0]?.id;
      }
      formApi.setValues(data);

      // 更新校验规则
      switch (type.value) {
        case ActionEnum.EDIT: {
          await updateRules(DefApplicationConfig.Update, []);
          break;
        }
        default: {
          await updateRules(DefApplicationConfig.Save, []);
          break;
        }
      }
    } else {
      formApi.setValues(record.value);
    }
  },
  onConfirm() {
    formApi.validate().then(async (e: any) => {
      if (e.valid) {
        const values = await formApi.getValues();
        modalApi.setState({ loading: true, confirmLoading: true });
        try {
          switch (type.value) {
            case ActionEnum.EDIT: {
              await DefApplicationApi.update(values);
              break;
            }
            default: {
              values.id = null;
              await DefApplicationApi.save(values);
              break;
            }
          }

          createMessage.success('保存成功');
          gridApi.value?.reload();
          modalApi.close();
        } finally {
          modalApi.setState({ loading: false, confirmLoading: false });
        }
      }
    });
  },
});
defineExpose(modalApi);
</script>
<template>
  <Modal :title="$t(`common.title.${type}`)" class="w-[60%]">
    <div class="common-form">
      <EditForm />
    </div>
  </Modal>
</template>
<style scoped lang="less">
@import '#/assets/styles/common-form.less';
</style>
